package paymentSystem;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;

/**
 * Servlet implementation class PaymentSystemServlet
 */
public class PaymentSystemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PaymentSystemServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out=response.getWriter();
		String orderCode = request.getParameter("orderId");
		String confirmPayment = request.getParameter("confirmPayment");
		if (orderCode!=null&&confirmPayment==null){
			out.println(
					"<form action=\"PaymentSystemServlet\" method=\"get\">\n" +
					"<input type=\"hidden\" name=\"orderId\" value=\"" + orderCode +"\" />\n" +
					"<input type=\"hidden\" name=\"confirmPayment\" value=\"1\" />\n"+
					"<input type=\"submit\"></input>\n" +
					"<br>Click on the button for pay the order</br>" +
					"</form>");
		}
		else 
			if(orderCode!=null &&confirmPayment!=null ){
				PaymentSystem ps = injecPayementSystemBean();
				Integer orderId = Integer.valueOf(orderCode);
				int returnValue = ps.doPayment(orderId);
				if(returnValue==0) out.println("payment is ok");
				else if (returnValue==-1)out.println("there is a problem with the payment server, can you retry, please");
				else if (returnValue==-2)out.println("payment is arrived too late, we are sorry");
				else out.print("ERROR");
				
			}
			else out.print("ERROR");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.print("Payment servlet prima inject");
		PaymentSystem ps = injecPayementSystemBean();
		System.out.print("Payment servlet dopo inject");
		ps.paymentRedirect(Integer.parseInt(request.getParameter("orderId")));
		System.out.print("Payment servlet dopo payment redirect");
	}

	private PaymentSystem injecPayementSystemBean(){
		try {
			PaymentSystemServiceLocator paymentSystemServiceLocator = new PaymentSystemServiceLocator();
			paymentSystemServiceLocator.setPaymentSystemPortEndpointAddress( getServletContext().getInitParameter("PAYMENT_SYSTEM_URI") );
			return paymentSystemServiceLocator.getPaymentSystemPort();
			
		}catch(ServiceException e){
			return null; 
		}
	}
	
}
